import wechatConfig from '@/utils/jweixin'
import { SHARE_PATH_MAP, SHARE_PAGE_DATA_MAP, NO_WECHAT_CONFIG } from '@/config'
export default {
  data() {
    return {
      sharePathMap: SHARE_PATH_MAP,
      sharePageDataMap: SHARE_PAGE_DATA_MAP,
      currentShareData: {},
      routerChangeType: '',
      disAbleWexinInit: false,
    }
  },
  onLoad(option) {
    const options = option || this.$Route.query
    if (getApp().globalData.isWeixinConfig && getApp().globalData.isWeixinBrowser) {
      const { currentRoute } = this.$router
      const { path, type } = currentRoute

      // 路由模块设置不需要微信授权
      if (NO_WECHAT_CONFIG.includes(path)) {
        this.disAbleWexinInit = true
        return
      }

      this.routerChangeType = type
      // 默认页面分享出去为首页
      let shareDataKey = 'index'
      if (this.sharePathMap[path]) {
        shareDataKey = this.sharePathMap[path]
      }
      this.currentShareData = this.sharePageDataMap[shareDataKey]
      if (this.currentShareData.paramsList && this.currentShareData.paramsList.length > 0) {
        for (const item in options) {
          if (this.currentShareData.paramsList.includes(item)) {
            if (this.currentShareData.url.indexOf('?') > -1) {
              this.currentShareData.url += `&${item}=${options[item]}`
            } else {
              this.currentShareData.url += `?${item}=${options[item]}`
            }
          }
        }
      }
    }
  },
  created() {
    
    
  },
  mounted() {

    if (getApp().globalData.isWeixinConfig && getApp().globalData.isWeixinBrowser && !this.disAbleWexinInit) {
      const page = getCurrentPages()
      // 当前页面为打开链接的第一个页面
      if (page.length === 1 && this.routerChangeType !== 'switchTab') {
        uni.$on('readyWeixinConfigInit', () => {
          this.initShare()
        })
      } else {
        this.initShare()
      }
    }
  },
  methods: {
    initShare() {
      wechatConfig.weiXinBrowerShare(this).then(() => {
        wechatConfig.buildShareContent({
          title: this.currentShareData.title,
          desc: this.currentShareData.content,
          shareLink: this.currentShareData.url,
          shareImg: this.currentShareData.image,
        })
      })
    },
  },
}